package com.apache.ius.interceptor;

import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.ius.common.annotion.BeanFactory;
import com.apache.rpc.common.XMLMapParse;
import com.apache.tools.ConfigUtil;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * description: 过滤器父类
 *
 * @author dyh 创建时间：2019年02月11日
 */
public abstract class SuperInterceptor implements HandlerInterceptor {

    //    @Autowired
    //    @Qualifier("xxx")
    //    protected XxxService xxx;

    public abstract boolean bodyHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, String message) throws Exception;

    public abstract boolean exeHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        init(request, response);
        //获取请求报文
        String messages = IOUtils.toString(request.getInputStream(), "UTF-8");
        if (Validator.isNotNull(messages)) {
            return bodyHandle(request, response, handler, messages);
        }
        return exeHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o,
            Exception e) throws Exception {
        //IOUtils.closeQuietly(response.getOutputStream());
    }

    /**
     * description:  获取请求参数
     */
    @SuppressWarnings("rawtypes")
    protected Map<String, String> getParameterMap(HttpServletRequest request) throws IOException {
        String ifBatch = StrUtil.doNull(request.getParameter("ifBatch"), "F");
        Map<String, String> map = new HashMap<String, String>();
        String reqIp = RequestTools.getIp(request);
        map.put("Client-IP", reqIp);
        Set keSet = request.getParameterMap().entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            String ok = String.valueOf(me.getKey());
            if ("ifBatch".equalsIgnoreCase(ok))
                continue;
            Object ov = me.getValue();
            String value = "";
            if (ov instanceof String[]) {
                String[] vls = (String[]) ov;
                if ("F".equalsIgnoreCase(ifBatch)) {//单表插入
                    value = vls[0];
                } else {
                    for (int i = 0; i < vls.length; i++) {////批量处理
                        if (i == vls.length - 1) {
                            value += StrUtil.doNull(vls[i], "_");
                        } else {
                            value += StrUtil.doNull(vls[i], "_") + "-#-";
                        }
                    }
                }
            } else {
                value = String.valueOf(ov);
            }
            if (StrUtil.isNotNull(value)) {
                String str = new String(value.getBytes("iso8859-1"), "iso8859-1");
                if (value.equals(str)) {
                    value = str;
                }
                map.put(ok, value);
            } else {
                if (ok.indexOf("s_") != -1) {
                    map.put(ok, "is null");//清空
                }
            }
        }
        map.put("sysPass", ConfigUtil.getInstance().interfacePass());
        return map;
    }

    protected Map<String, Object> getParameterMap(String paramsStr){
        if (paramsStr.startsWith("<?")) {//xml方式传入
            Map<String, Object> headMap = new HashMap<String, Object>();
            Map<String, Object> bodyMap = new HashMap<String, Object>();
            XMLMapParse.instance().xmlGetData(paramsStr, headMap, bodyMap);
            return bodyMap;
        }else{
            return json2Map(paramsStr);
        }
    }

    /**
     * 将json字符串转为Map结构
     * 如果json复杂，结果可能是map嵌套map
     * @param jsonStr 入参，json格式字符串
     * @return 返回一个map
     */
    protected Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else if (v instanceof JSONObject) {
                    map.put(k.toString(), json2Map(v.toString()));
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }

    /**
     * description:  跳到登录页面
     */
    protected JSONObject gotoLogin(HttpServletRequest request, HttpServletResponse response,
            String msg) throws IOException {
        ResultMsg rmsg = new ResultMsg("F", StrUtil.doNull(msg, "您还没有登录，请您先登录再进行相应操作"));
        JSONObject array = JSONObject.fromObject(rmsg);
        return array;
    }

    /**
     * description:  跳到登录页面
     */
    protected void sendLogin(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        //定自义登录页面
        String customLogin = ToolsUtil.getInstance().getValueByKey("custom_login");
        response.sendRedirect(request.getContextPath() + StrUtil.doNull(customLogin, "/"));
    }

    private void init(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        BeanFactory.getInstance().checkSysFlag();
    }

    /**
     * 输出json数据
     *
     * @param json
     * @param response
     */
    protected void outputJson(String json, HttpServletResponse response, String callback)
            throws IOException {
        if (StrUtil.isNotNull(json)) {
            PrintWriter out = response.getWriter();
            if (StrUtil.isNull(callback)) {
                response.setContentType("text/html;charset=UTF-8");
                /**
                 * 解决外部系统跨域访问，Access-Control-Allow-Origin的提示
                 * xhe 20171107
                 * 思路来自：http://blog.csdn.net/fdipzone/article/details/46390573/
                 */
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST,GET");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
                out.print(json);
            } else {
                response.setContentType("application/javascript");
                out.print(callback + "(" + json + ")");
            }
            out.flush();
            out.close();
        }
    }
}
